package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;

import com.itheima.pojo.Menu;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.service.MenuService;
import com.itheima.service.PermissionService;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;

import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.*;

@RestController
@RequestMapping("/user")
public class UserController {
    @Reference
    UserService userService;
    @Reference
    MenuService menuService;
    @Autowired
    private PasswordEncoder passwordEncoder;

    //获取当前登录用户的用户名
    @RequestMapping("/getUsername")
    public Result getUsername(){

        try {
            org.springframework.security.core.userdetails.User user =
                    (org.springframework.security.core.userdetails.User)
                            SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            return new Result(true, MessageConstant.GET_USERNAME_SUCCESS,user.getUsername());
        } catch (Exception e){
            return new Result(false, MessageConstant.GET_USERNAME_FAIL);
        }
    }
    //获取当前登录失败信息
    @RequestMapping("/getloginmessage")
    public Result getloginmessage(HttpServletRequest req)throws Exception {
        //获取异常的session
        HttpSession session = req.getSession();
        Exception spring_security_last_exception = (Exception) session.getAttribute("SPRING_SECURITY_LAST_EXCEPTION");
        if (spring_security_last_exception!=null) {

            String message = spring_security_last_exception.getMessage();
            //销毁session
            session.removeAttribute("SPRING_SECURITY_LAST_EXCEPTION");
            System.out.println(message);
            if (message.equals("Bad credentials")){
                //销毁session
                session.removeAttribute("SPRING_SECURITY_LAST_EXCEPTION");
                return new Result(false,"密码错误");
            }
            return new Result(false,message);
        }
        return new Result(true,"未登录");
    }

    //登陆后显示对应权限的菜单
    @RequestMapping("/roles")
    public Result roles(String username){
        try{
            List<Menu> list=new ArrayList<>();
            Menu menuother = new Menu();
            com.itheima.pojo.User user=userService.findAllUsername(username);
            Set<Role> roles = user.getRoles();
            List<Integer> menuid=new ArrayList<>();
            List<Integer> menuParentId=new ArrayList<>();
            for (Role role : roles) {
                LinkedHashSet<Menu> menus = role.getMenus();

                //将id和父id存入集合
                for (Menu menu : menus) {
                   if (menu.getId()!=null){
                       menuid.add(menu.getId());
                   }
                   if (menu.getParentMenuId()!=null){
                       menuParentId.add(menu.getParentMenuId());
                   }
                }
                //将一级菜单加入到list集合

                for (Menu menu : menus) {
                    if (menu.getLevel()==1){
                        list.add(menu);
                    }

                }
                   //一级以下菜单,但没有父菜单权限,需要加入到父菜单中
                  //如果父id在id在id集合中没有,要根据父id查找父菜单,并把此子菜单加入
                Integer level=1;
               List<Menu> level1=menuService.findByMenuLevel1(level);
                for (Menu menu : level1) {
                    for (Menu menu1 : menus) {
                        //不是一级菜单
                        if (menu1.getParentMenuId()!=null){
                            int count=0;

                            for (Integer integer : menuid) {
                                if (menu1.getParentMenuId()==integer){
                                    count++;
                                }
                            }
                            //此角色的此子菜单没有父级菜单
                            if (count==0&&(menu1.getParentMenuId()==menu.getId())){
                                ArrayList<Menu> menus1 = new ArrayList<>();
                                menus1.add(menu1);
                                menu.setChildren(menus1);
                            }

                        }
                    }
                }
                for (Menu menu : level1) {
                    if (menu.getChildren()!=null&&menu.getChildren().size()>0){
                        list.add(menu);
                    }
                }
            }
            System.out.println(list);
            return new Result(true,"success",list);

        }catch (Exception e){
            e.printStackTrace();
            return new Result(false,"failure");
        }
    }

    //查询所有用户
    @RequestMapping("/findPage")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean) throws Exception {
        PageResult pageResult = userService.findPage(
                queryPageBean.getCurrentPage(),
                queryPageBean.getPageSize(),
                queryPageBean.getQueryString());
        return pageResult;
    }

    //修改用户状态
    @RequestMapping("/station")
    public Result updateStation(@RequestParam Map map) {
        try {
            Integer station= Integer.parseInt((String)map.get("station"));
            Integer id= Integer.parseInt((String)map.get("id"));
            userService.updateStation(station, id);
            return new Result(true, MessageConstant.EDIT_USER_STATION_SUCCESS);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false,MessageConstant.EDIT_USER_STATION_FAIL);
        }
    }

    //新增用户
    @RequestMapping("/add")
    public Result add(@RequestBody User user) {
        try {
            String password = user.getPassword();
            //获取编译密码器进行密码加密
            String encode = passwordEncoder.encode(password);
            user.setPassword(encode);
            userService.add(user);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.ADD_USER_FAIL);
        }
        return new Result(true, MessageConstant.ADD_USER_SUCCESS);
    }

    //编辑用户回显
    @RequestMapping("/findById")
    public Result findById(Integer id) {
        try {
            User user = userService.findById(id);
            return new Result(true, MessageConstant.ECHO_USER_SUCCESS, user);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.ECHO_USER_FAIL);
        }
    }

    //编辑用户确认
    @RequestMapping("/updateById")
    public Result updateById(@RequestBody User user) {
        try {
            userService.updateById(user);
            return new Result(true, MessageConstant.EDIT_USER_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.EDIT_USER_FAIL);
        }
    }

    //查询语句
    @RequestMapping("/findBy")
    public Result updateById(Integer id) {
        User user = userService.findById(id);
        return new Result(true, MessageConstant.GET_USER_SUCCESS, user);
    }

    //修改用户密码
    @RequestMapping("/updatePassword")
    public Result updatePassword(@RequestBody Map map) {
        String cipher = (String) map.get("cipher");
        String cryptogram = (String) map.get("cryptogram");
        Integer id = (Integer) map.get("id");
        if (cipher != null && cryptogram != null && cipher.equals(cryptogram)) {
            String password = passwordEncoder.encode(cipher);
            userService.updatePassword(id, password);
        } else {
            return new Result(false, MessageConstant.EDIT_USER_PASSWORD_FAIL);
        }
        return new Result(true, MessageConstant.EDIT_USER_PASSWORD_SUCCESS);
    }

    //删除用户
    @RequestMapping("/delete")
    public Result delete(Integer id) {
        try {
            userService.delete(id);
            return new Result(true, MessageConstant.DELETE_USER_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.DELETE_USER_FAIL);
        }
    }

    //查询角色
    @RequestMapping("/AddingRoles")
    public Result AddingRoles() {
        List<Role> role = userService.AddingRoles();
        if (role != null && role.size() > 0) {
            return new Result(true, MessageConstant.GET_ROLE_SUCCESS, role);
        } else {
            return new Result(false, MessageConstant.GET_ROLE_FAIL);
        }
    }

    //回显复选框
    @RequestMapping("/findByUserAndRole")
    public Result findByUserAndRole(Integer id) {
        try {
            List<Integer> findByUserAndRole = userService.findByUserAndRole(id);
            return new Result(true, MessageConstant.QUERY_ROLES_SUCCESS, findByUserAndRole);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.QUERY_ROLES_FAIL);
        }
    }

    //角色授权
    @RequestMapping("/RoleAuthorization")
    public Result RoleAuthorization(@RequestBody User user, Integer[] role) {
        try {
            Integer userId = user.getId();
            userService.RoleAuthorization(userId, role);
            return new Result(true,MessageConstant.GET_ROLE_AUTHORITY_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.GET_ROLE_AUTHORITY_FAIL);
        }
    }


}
